package com.dyzx.hbb.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyzx.hbb.modules.sys.entity.SysRoleUser;
import com.dyzx.hbb.modules.sys.service.SysRoleUserService;
import com.dyzx.hbb.modules.sys.mapper.SysRoleUserMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【sys_role_user(用户配置角色表)】的数据库操作Service实现
* @createDate 2025-04-14 13:29:08
*/
@Service
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserMapper, SysRoleUser>
    implements SysRoleUserService {

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        // 根据角色ID查询所有用户ID
        return this.baseMapper.selectList(
            new LambdaQueryWrapper<SysRoleUser>()
                .eq(SysRoleUser::getRoleId, roleId)
                .select(SysRoleUser::getUserId)
        ).stream().map(SysRoleUser::getUserId).collect(Collectors.toList());
    }

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        // 根据角色ID查询所有用户ID
        return this.baseMapper.selectList(
                new LambdaQueryWrapper<SysRoleUser>()
                        .eq(SysRoleUser::getUserId, userId)
                        .select(SysRoleUser::getRoleId)
        ).stream().map(SysRoleUser::getRoleId).collect(Collectors.toList());
    }

    @Override
    public boolean deleteRoleUsers(Long roleId, List<Long> userIds) {
        // 批量删除角色下的用户
        return this.remove(
            new LambdaQueryWrapper<SysRoleUser>()
                .eq(SysRoleUser::getRoleId, roleId)
                .in(SysRoleUser::getUserId, userIds)
        );
    }

    @Override
    public boolean assignUsers(Long roleId, List<Long> userIds) {
        // 批量分配用户到角色
        List<SysRoleUser> userRoles = userIds.stream().map(userId -> {
            SysRoleUser userRole = new SysRoleUser();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            return userRole;
        }).collect(Collectors.toList());
        return this.saveBatch(userRoles);
    }

    @Override
    public void userByRoles(Long id, List<Long> roleIds) {
        if (roleIds != null && !roleIds.isEmpty()) {
        // 先删除用户原有的所有角色
        this.remove(new LambdaQueryWrapper<SysRoleUser>()
                .eq(SysRoleUser::getUserId, id));

        // 为用户分配新的角色

            List<SysRoleUser> userRoles = roleIds.stream().map(roleId -> {
                SysRoleUser userRole = new SysRoleUser();
                userRole.setUserId(id);
                userRole.setRoleId(roleId);
                return userRole;
            }).collect(Collectors.toList());
            this.saveBatch(userRoles);
        }
    }
}




